package com.example.adapter;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.db.CommonData;
import com.example.im.R;
import com.example.model.Friends;
import com.example.model.Msg;
import com.example.model.User;
import com.example.util.MyUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.stream.Collectors;

import static com.example.db.CommonData.addDbFriend;
import static com.example.db.CommonData.commonData;
import static com.example.db.CommonData.getDbFriendList;
import static com.example.db.CommonData.getDbMsg;
import static com.example.db.CommonData.getDbUserList;
import static com.example.db.CommonData.writeData;
import static com.example.util.MyUtil.exeUrlTask;
import static com.example.util.MyUtil.myUtil;
import static com.example.util.MyUtil.toast;

public class AddFriendListAdapter extends BaseAdapter {
    private final LayoutInflater inflater;
    private final List<User> mData;
    private final Context context;
    public AddFriendListAdapter(Context context, List<User> data) {
        this.context = context;
        inflater = LayoutInflater.from(context);
        this.mData = data;
    }

    // 要绑定的条目的数目
    @Override
    public int getCount() {
        return mData.size();
    }

    // 根据一个索引（位置）获得该位置的对象
    @Override
    public Object getItem(int position) {
        return mData.get(position);
    }

    // 获取条目的id
    @Override
    public long getItemId(int position) {
        return position;
    }

    // 获取该条目要显示的界面
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        AddFriendHolder holder;
        // 第一次加载条目时，初始化界面和相应函数
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.friend_list_item, parent, false);
            holder = new AddFriendHolder();
            holder.addFriendButton = (Button) convertView.findViewById(R.id.add_button);
            holder.name = (TextView) convertView.findViewById(R.id.friend_name);
            holder.id = (TextView) convertView.findViewById(R.id.uid);
            convertView.setTag(holder);

            initAddFriendButtonEvent(holder);
        } else {
            holder = (AddFriendHolder) convertView.getTag();
        }
        User user = mData.get(position);
        holder.name.setText(user.getName());
        holder.id.setText(String.valueOf(user.getId()));
        return convertView;
    }

    /**
     * 初始化添加好友按钮相应方法
     * @param holder
     */
    private void initAddFriendButtonEvent(AddFriendHolder holder) {

        holder.addFriendButton.setOnClickListener(e -> {
            final AddFriendHolder HOLDER = holder;
            String name = HOLDER.name.getText().toString();
            // TODO:添加好友按钮相应方法
            exeUrlTask(context,
                    () ->MyUtil.getReqParam("/imChatUserFriend/addFriend",
                            MyUtil.paramMap(Collections.singletonList("friendId"),
                                    Collections.singletonList(holder.id.getText().toString()))),
                    res -> {
                        User user = mData.stream().filter(u -> Objects.equals(u.getName(), name)).findFirst().orElse(null);
                        assert user != null;
//                        MyUtil.initFirstMsg(user.getName(),user.getId(),context);

                        if (addDbFriend(commonData.getUser(), user)) {
                            Friends friends=new Friends();
                            friends.setUid(commonData.getUser().getId());
                            friends.setFid(user.getId());
                            friends.setName(user.getName());
                            mData.remove(user);
                        }
                        toast(context,"添加 "+user.getName()+" 为好友成功");

                        // 剔除该用户
                        notifyDataSetChanged();
                        writeData(context);
                    }
            );

        });
    }

    public void flush(String query) {
        //接口获取所有用户信息
        exeUrlTask(context,
                () -> MyUtil.postReqJson("/admin/user/list",
                        new HashMap<>()),
                        res -> ((Activity) context).runOnUiThread(() -> {
                    /* 数组
                    {
    "code": 200,
    "message": null,
    "data": {
        "records": [
            {
                "id": 2,
                "username": "1",
                "password": null,
                "phoneNumber": null,
                "email": null,
                "userStatus": true,
                "gender": null,
                "openId": null,
                "avatar": null,
                "admire": null,
                "subscribe": null,
                "introduction": null,
                "userType": 2,
                "createTime": "2024-01-05T14:29:23",
                "updateTime": "2024-01-05T21:58:12",
                "updateBy": null,
                "deleted": false,
                "loginIp": "39.144.190.122"
            }
        ],

    },
    "currentTimeMillis": 1704472851793
}
                     */
                            JSONObject data = res.getDataObject();
                            JSONArray records = data.getJSONArray("records");
                            List<User> totalUserList=new ArrayList<>();
                            for (int i = 0; i < records.size(); i++) {
                                JSONObject person = records.getJSONObject(i);
                                String name = person.getString("username");
                                int id = person.getInteger("id");
                                User user = new User();
                                user.setName(name);
                                user.setId(id);
                                user.setLoginIp(person.getString("loginIp"));
                                totalUserList.add(user);
                            }
                            String curName = commonData.getUser().getName();
                            int uid = commonData.getUser().getId();
                            List<Friends> dbFriendList = getDbFriendList(curName);
                            List<User> dbUserList = totalUserList.stream().filter(u ->
                                    !Objects.equals(curName, u.getName()) &&
                                            u.getName().contains(query) &&
                                            dbFriendList.stream().noneMatch(f -> Objects.equals(f.getUid(), u.getId())
                                                    ||Objects.equals(f.getFid(),u.getId()))
                            ).collect(Collectors.toList());
                            mData.clear();
                            mData.addAll(dbUserList);
//                            toast(context,"查询用户列表成功");
                            notifyDataSetChanged();
                        }),
                r -> toast(context, r.getMessage()+"异常"));
    }

    // 新建holder类，对listview进行简单优化
    public static class AddFriendHolder {
        Button addFriendButton;
        TextView name;
        TextView id;
    }
}